/*
 * @Author: wyf 844650674@qq.com
 * @Date: 2022-10-14 09:06:43
 * @LastEditors: wyf 844650674@qq.com
 * @LastEditTime: 2022-10-14 09:22:42
 * @FilePath: \sports\admin-server\router\common\index.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
module.exports = (app) => {
  const express = require("express");
  const router = express.Router({
    // mergeParams: true // 让路由获取到'/admin/api/rest/:resource'的resource参数
  });
  // 新增
  router.post("/", async (req, res) => {
    const model = req.Model.create(req.body);
    res.send(model);
  });

  // 编辑
  router.put("/:id", async (req, res) => {
    const model = await req.Model.findByIdAndUpdate(req.params.id, req.body);
    res.send(model);
  });

  // 查询所有
  router.get("/", async (req, res) => {
    const queryOption = {};
    if (req.Model.modelName === "Category") {
      queryOption.populate = "parent";
    }
    // if (req.Model.modelName === 'Hero') {
    //   queryOption.populate = 'categories'
    // }
    const items = await req.Model.find().setOptions(queryOption);
    res.send(items);
  });

  // 通过id查询
  router.get("/:id", async (req, res) => {
    const item = await req.Model.findById(req.params.id);
    res.send(item);
  });

  // 删除
  router.delete("/:id", async (req, res) => {
    const model = await req.Model.findByIdAndDelete(req.params.id);
    res.send(model);
  });

  app.use(
    "/v1/admin/api/rest/:resource",
    async (req, res, next) => {
      req.Model = require(`../../model/${req.params.resource}`);
      next();
    },
    router
  );
};
